import React, { useState } from "react";
import { Button, Divider, Row, Col, Space, Upload,message } from "antd";
import "./comments.scss";
import CommentsList from "./CommentsList";
import BraftEditor from "braft-editor";
import "braft-editor/dist/index.css";
import { ContentUtils } from "braft-utils";
import axios from "axios";
import moment from 'moment';
import Qs from 'qs' ;
import {connect} from 'react-redux';
function Index({UpateUserInfo}) {
  const [comment, setComment] = useState(false);
  const [editorState, seteditorState] = useState(BraftEditor.createEditorState(null));
  const [editorInstance, seteditorInstance] = useState();
  const [flag,setFlag] = useState(false) ;
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [dataList, setDatalist] = useState([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const uploadHandler = function () {};
  const buildPreviewHtml = function() {
    return `
    <!Doctype html>
    <html>
      <head>
        <title>Preview Content</title>
        <style>
          html,body{
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: auto;
            background-color: #f1f2f3;
          }
          .container{
            box-sizing: border-box;
            width: 1000px;
            max-width: 100%;
            min-height: 100%;
            margin: 0 auto;
            padding: 30px 20px;
            overflow: hidden;
            background-color: #fff;
            border-right: solid 1px #eee;
            border-left: solid 1px #eee;
          }
          .container img,
          .container audio,
          .container video{
            max-width: 100%;
            height: auto;
          }
          .container audio {
            height:40px
          }
          .container p{
            white-space: pre-wrap;
            min-height: 1em;
          }
          .container pre{
            padding: 15px;
            background-color: #f1f1f1;
            border-radius: 5px;
          }
          .container blockquote{
            margin: 0;
            padding: 15px;
            background-color: #f1f1f1;
            border-left: 3px solid #d1d1d1;
          }
        </style>
      </head>
      <body>
        <div class="container">${editorState.toHTML()}</div>
      </body>
    </html>
  `
  }
  const preview = function() {
    if (window.previewWindow) {
      window.previewWindow.close()
    }

    window.previewWindow = window.open()
    window.previewWindow.document.write(buildPreviewHtml())
    window.previewWindow.document.close()
  }
  
  const extendControls = [
    {
      key: 'custom-button',
      type: 'button',
      text: '预览',
      onClick: preview
    }
  ];
  const getData = async (current, pageSize) => {
    setLoading((prev) => true);
    let { data: res } = await axios.get("/api/allcomments", {
      params: { current, pageSize,userid:UpateUserInfo.userInfo.id },
    });
    console.log(res.length);
    if (res.ok !== 1) {
      return message.error(res.message);
    }
    let datas = res.datalist.map((item) => {
      item.comments = BraftEditor.createEditorState(new Buffer(item.comments).toString()).toHTML();
      return item;
    });
    setTotal((prev) => res.total);
    setDatalist((prev) => [...datas]);
    setLoading((prev) => false);
    console.log(res);
  };
  const handleEditorChange = function (editor) {
    // setEditorState((prev) => editor);
    console.log(editorState.toRAW(true));
    seteditorState((prev) => editor);
    
  };
  const hooks = {
    'toggle-link': ({ href, target }) => {
      const pattern = /^((ht|f)tps?):\/\/([\w-]+(\.[\w-]+)*\/?)+(\?([\w\-.,@?^=%&:/~+#]*)+)?$/
      if (pattern.test(href)) {
          return { href, target }
      }
      message.warning('请输入完整的正确的网址,必须添加协议头')
      return false
  }
  }
  const uploadFnQiNiu = async function (param) {
    const xhr = new XMLHttpRequest();
    let { data: res } = await axios.get("/api/uptoken",{
      params:{
        userid:UpateUserInfo.userInfo.id,
      }
    });
    const formData = new FormData();
    formData.append("file", param.file);
    formData.append('token',res.uptoken);
    formData.append('key',res.key) ;
    // const result = await fetch("http://up-z2.qiniu.com/", {
    //   method: "post",
    //   body: formData,
    // }).then((response) => response.json());
    // console.log(result) ;
    const successFn = (response) => {
      // 假设服务端直接返回文件上传后的地址
      // 上传成功后调用param.success并传入上传后的文件地址
      let data = JSON.parse(xhr.responseText)
      param.success({
        url: 'http://imaegs.chenzefan.xyz/' + data.key,
        meta: {
          id:  data.key + '',
          title:'usersmedia'+ data.key + '' ,
          alt: 'mdiachenzefan'+ data.key,
          loop: false, // 指定音视频是否循环播放
          autoPlay: false, // 指定音视频是否自动播放
          controls: true, // 指定音视频是否显示控制栏
          // poster: false, // 指定视频播放器的封面
        }
      })
    }
  
    const progressFn = (event) => {
      // 上传进度发生变化时调用param.progress
      param.progress(event.loaded / event.total * 100)
    }
  
    const errorFn = (response) => {
      // 上传发生错误时调用param.error
      param.error({
        msg: '上传错误'
      })
    }
  
    xhr.upload.addEventListener("progress", progressFn, false)
    xhr.addEventListener("load", successFn, false)
    xhr.addEventListener("error", errorFn, false)
    xhr.addEventListener("abort", errorFn, false)
  
    xhr.open('POST', "http://up-z2.qiniu.com/", true)
    xhr.send(formData)
    
  };
  const submitContent = function () {};
  const submitComments = async function() {

    let flag = false ;
    let flag1 = false ;
    editorState.toRAW(true).blocks.forEach((item)=> {
      if(item.text.trim(' ') !== '') {
              flag = true
              return ;
      }
    })
    for(let key in editorState.toRAW(true).entityMap) {
      flag1 = true
    };
    if(editorState.isEmpty() || (!flag&&!flag1)) {
      return message.warning('评论内容不可以为空或全为空格');
    }
    let {data:res} = await axios.post('/api/postcomments',Qs.stringify({
      comments:editorState.toRAW(),
      currenttime:moment().unix(),
      userid:UpateUserInfo.userInfo.id,
    }),{
      headers:{
        'Content-type': 'application/x-www-form-urlencoded'
      }
    })
     if(res.ok !== 1) {
       return message.error(res.message) ;
     }
     message.success(res.message);
     seteditorState(prev => ContentUtils.clear(editorState));
     setCurrent(prev => 1) ;
     getData(1,pageSize) ;
  }
  return (
    <div>
    <div className="comments">
      {comment ? (
        <Row justify="center" gutter={[30, 35]} style={{ width: "75%" }}>
          <Col span={24}>
            <BraftEditor
              hooks={hooks}
              media={{ uploadFn: uploadFnQiNiu }}
              extendControls={extendControls}
              ref={(instance) => seteditorInstance((prev) => instance)}
              value={editorState}
              onChange={handleEditorChange}
              onSave={submitContent}
            />
          </Col>
          <Col>
            <Space size={64}>
              <Button
                type="default"
                size="middle"
                onClick={async() => {
                  setComment(false);
                  // 清空编辑器 这个清空没问题
                  seteditorState(prev => ContentUtils.clear(editorState));
                  // editorInstance.clearEditorContent();
                 
                }}
              >
                取消
              </Button>
              <Button
                type="danger"
                siez="middle"
                onClick={submitComments}
              >
                提交
              </Button>
            </Space>
          </Col>
        </Row>
      ) : (
        <Button
          type="primary"
          shape="round"
          size="large"
          onClick={() => {
            setComment(true);
          }}
        >
          评&emsp;论
        </Button>
      )}

      <Divider style={{ height: "3px", fontWeight: 700, color: "#85b4f7" }}>Comments</Divider>
      <CommentsList current={current} setCurrent={setCurrent} pageSize={pageSize} setPageSize={setPageSize} loading={loading} total={total} dataList={dataList} getData={getData} />
    </div>
    </div>
  );
}

export default connect(state=>state)(Index);
